package com.cssy.yd.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicStorageService;
import com.cssy.yd.logic.entity.LogicWhmoveInwhDO;
import com.cssy.yd.logic.entity.LogicWhmoveInwhItemDO;
import com.cssy.yd.logic.entity.LogicWhmoveOutwhDO;
import com.cssy.yd.logic.entity.LogicWhmoveOutwhItemDO;
import com.cssy.yd.logic.service.ILogicStockTransferEndService;
import com.cssy.yd.logic.service.ILogicStockTransferItemEndService;
import com.cssy.yd.logic.service.ILogicStockTransferItemStartService;
import com.cssy.yd.logic.service.ILogicStockTransferStartService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/yd/logic/stockTransferEnd")
public class StockTransferEndController extends BaseController<LogicWhmoveInwhDO>{

	private static final String MANAGER = "/yd/logic/stockTransfer/ManagerEnd";
	private static final String EIDT = "/yd/logic/stockTransfer/OperationEnd";//添加、修改、显示页面
	@Resource(name = "logicStockTransferEndService")
	private ILogicStockTransferEndService logicStockTransferEndService;
	
	@Resource(name = "logicStockTransferItemEndService")
	private ILogicStockTransferItemEndService logicStockTransferItemEndService;
	
	@Resource(name="logicStockTransferItemStartService")
	private ILogicStockTransferItemStartService logicStockTransferItemStartService;
	
	@Resource(name="logicStockTransferStartService")
	private ILogicStockTransferStartService logicStockTransferStartService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;

	@Resource(name = "basicwhService")
	private IBasicStorageService basicwhService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("wh1",basicwhService.findwh(request));
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setOrderBy("dctime desc");
		Map<String, Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request,
				scUserRolePlaceService, "whcode");
		scs.addCondition((String) sqlMap.get("option"),
				(List) sqlMap.get("roleWhList"));
		SearchResult result = logicStockTransferEndService
				.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}

	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable  String flag, Model model) throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("xx", 1);//标示能不能修改内容
			SearchConditions scs = new SearchConditions();
			scs.setOrderBy("dctime desc");
			scs.addCondition("intype","0,1",SearchCondition.OP_IN);
			scs.addCondition("billstatus","3",SearchCondition.OP_EQUAL);
			Map<String, Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request,
					scUserRolePlaceService, "whcode");
			scs.addCondition("inwhcode",(List) sqlMap.get("roleWhList"));
			SearchResult sr1 = logicStockTransferStartService.findListByExample(scs);
			model.addAttribute("ori", sr1.getResults());
		}else{
			LogicWhmoveInwhDO oi = logicStockTransferEndService.findListById(id);
			if (oi.getBillstauts() == 0){
				model.addAttribute("xx", 1);//标示能不能修改内容
			}
			//List<LogicWhmoveInwhItemDO> loiilist = logicStockTransferItemEndService.getLogicWhmoveInwhItemByOtherInwhId(id);	
			model.addAttribute("oi", oi);
			//model.addAttribute("axxJson", loiilist);
		}
		
		return EIDT;
	}

	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicWhmoveInwhItemDO> loiilist = logicStockTransferItemEndService.getLogicWhmoveInwhItemByOtherInwhId(id);
			OutJsonGrid out = new OutJsonGrid(loiilist);
			out.printJSon(response);
		}
	}
	
	@Override	
	public Map<String, Object> save(HttpServletRequest request,
			LogicWhmoveInwhDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if(itemdata==null&&"".equals(itemdata)){
				bodyMap.isFail();
				bodyMap.configWebInfor("物料不能为空！");
				return bodyMap.modelMap;
			}
			if(curAP.getBillstauts()==0||curAP.getBillstauts()==1){
				logicStockTransferEndService.endsave(curAP, request);
			}else{
				logicStockTransferEndService.checkSave(curAP, request);
			}
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicWhmoveInwhDO li=logicStockTransferEndService.findListById(field);
				li.setRemoved(Short.parseShort("1"));
				logicStockTransferEndService.update(li, SessionUtil.getUser(request));
			}
		
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 选择调拨单据返回详细信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/stoTraItemList")
	public void stoTraItemList(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception{
		SearchConditions scs = new SearchConditions();
		String oricode = request.getParameter("oricode");  //发起单号编码
		scs.addCondition("otheroutwhcode",oricode,SearchCondition.OP_EQUAL);
		scs.addCondition("billstatus","3",SearchCondition.OP_EQUAL);
		scs.addCondition("intype","0,1",SearchCondition.OP_IN);
		 SearchResult sr = logicStockTransferStartService.findListByExample(scs);
		 if(sr == null || sr.getResults().size() < 1){
			 throw new Exception("错误: 此调拨发起单无子项存在不能接收!!");
		 }
		 
		 LogicWhmoveOutwhDO logicWhmoveOutwhDO = (LogicWhmoveOutwhDO) sr.getResults().get(0);//根据调拨发起单据编码获取单据信息		 		 
		 List<LogicWhmoveOutwhItemDO> lwoidList = logicStockTransferItemStartService.getLogicWhmoveOutwhItemByOtherOutwhId(logicWhmoveOutwhDO.getId());		 
			 
		 SearchResult result= new SearchResult();
		 result.setResults(this.trLogicWhmoveOutwhItemDOToLogicWhmoveInwhItemDO(lwoidList,oricode));
		 result.setRecordCount(this.trLogicWhmoveOutwhItemDOToLogicWhmoveInwhItemDO(lwoidList,oricode).size());
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
	}
	
	/**
	 * 将调拨发起单行项目信息转存入调拨接收行项目对象中
	 * @param lwoidList
	 * @param oricode
	 * @return
	 */
	public List<LogicWhmoveInwhItemDO> trLogicWhmoveOutwhItemDOToLogicWhmoveInwhItemDO(List<LogicWhmoveOutwhItemDO> lwoidList, String oricode){
		
		List<LogicWhmoveInwhItemDO> lwidList = new ArrayList<LogicWhmoveInwhItemDO>();
		List<LogicWhmoveInwhDO> historyin = new ArrayList<LogicWhmoveInwhDO>();

		SearchConditions scs = new SearchConditions();
		SearchResult sr = new SearchResult();
		scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
		scs.addCondition("billstauts","3", SearchCondition.OP_EQUAL);  //查询审核完成单据
		sr = logicStockTransferEndService.findListByExample(scs);
		if(sr.getRecordCount()>0){ //有历史接收记录
			historyin = sr.getResults();
			for(LogicWhmoveOutwhItemDO lwoid : lwoidList){
				BigDecimal tempysQuantity = new BigDecimal("0.0");
				Double ysQuantity = Double.parseDouble("0.0"); //已接收数量
				Double wsQuantity = Double.parseDouble("0.0"); //未接收数量
				LogicWhmoveInwhItemDO lwid = new LogicWhmoveInwhItemDO();
				lwid.setCode(lwoid.getCode());
				lwid.setName(lwoid.getName());
				lwid.setQuantity1(lwoid.getQuantity());    //发起数量（单位）
				lwid.setInquantity(lwoid.getJquantity());  //发起数量（基本单位）
				lwid.setJunit(lwoid.getJunit());
				lwid.setBatch(lwoid.getBatch());
				lwid.setBzq(lwoid.getBzq());
				lwid.setYxq(lwoid.getYxq());
				lwid.setScrq(lwoid.getScrq());
				lwid.setStatus(lwoid.getStatus());
				lwid.setMaterialsid(lwoid.getMaterialsid());
				lwid.setSpec(lwoid.getSpec());
				lwid.setUnit(lwoid.getUnit());
				lwid.setUnitconvert(lwoid.getUnitconvert());
				for(LogicWhmoveInwhDO hisin : historyin) { //历史接收单循环
					SearchConditions scs1 = new SearchConditions();
					SearchResult sr1 = new SearchResult();
					scs1.setRemovedProperty(null);
					scs1.addCondition("otherinwhid", hisin.getId(), SearchCondition.OP_EQUAL);
					scs1.addCondition("batch", lwid.getBatch(), SearchCondition.OP_EQUAL);
					scs1.addCondition("code",lwid.getCode(), SearchCondition.OP_EQUAL); 
					scs1.addCondition("status",lwid.getStatus(), SearchCondition.OP_EQUAL); 
					sr1 = logicStockTransferItemEndService.findListByExample(scs1);  //查找此物料的历史接收记录
					if(sr1.getRecordCount()>0){
						List<LogicWhmoveInwhItemDO> hislist = sr1.getResults();
						LogicWhmoveInwhItemDO hisitemdo = hislist.get(0);
						tempysQuantity = tempysQuantity.add(new BigDecimal(hisitemdo.getQuantity().toString())); 
						wsQuantity = new BigDecimal(lwid.getQuantity1().toString()).subtract(tempysQuantity).doubleValue();
						ysQuantity = tempysQuantity.doubleValue();
					}else if(sr1.getRecordCount()==0){
						wsQuantity = new BigDecimal(lwid.getQuantity1().toString()).subtract(tempysQuantity).doubleValue();
						ysQuantity = tempysQuantity.doubleValue();
					}
				}
				lwid.setHisQuantity(ysQuantity);
				lwid.setUnQuantity(wsQuantity);
				lwid.setQuantity(lwid.getUnQuantity());  //本次接收数量（单位）
				lwid.setJquantity(lwid.getUnQuantity()*lwid.getUnitconvert()); 	//本次接收数量（基本单位）
				lwidList.add(lwid);
			}
		} else{ //第一次接收
			for(LogicWhmoveOutwhItemDO lwoid : lwoidList){
				LogicWhmoveInwhItemDO lwid = new LogicWhmoveInwhItemDO();
				lwid.setCode(lwoid.getCode());
				lwid.setName(lwoid.getName());
				lwid.setQuantity1(lwoid.getQuantity());    //发起数量（单位）
				lwid.setInquantity(lwoid.getJquantity());  //发起数量（基本单位）
				lwid.setJunit(lwoid.getJunit());
				lwid.setBatch(lwoid.getBatch());
				lwid.setBzq(lwoid.getBzq());
				lwid.setYxq(lwoid.getYxq());
				lwid.setScrq(lwoid.getScrq());
				lwid.setStatus(lwoid.getStatus());
				lwid.setMaterialsid(lwoid.getMaterialsid());
				lwid.setQuantity(lwoid.getQuantity());  //本次接收数量（单位）
				lwid.setJquantity(lwoid.getJquantity()); 	//本次接收数量（基本单位）
				lwid.setSpec(lwoid.getSpec());
				lwid.setUnit(lwoid.getUnit());
				lwid.setUnitconvert(lwoid.getUnitconvert());
				lwid.setHisQuantity(Double.parseDouble("0.0"));  //已接收数量（单位）
				lwid.setUnQuantity(lwoid.getQuantity());  //未接收数量（单位）
				lwidList.add(lwid);
			}
		}
		return lwidList;
	}
	
	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String, String> map=new HashMap<String, String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicWhmoveInwhDO lot=logicStockTransferEndService.findListById(ids);
				if(lot.getId()!=null){
					lot.setBillstauts(Short.parseShort("0")); //驳回到草稿
					logicStockTransferEndService.update(lot, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
}
